import uuid
# from flaskapp.model.db import db, Alarm, MediaSource,User,Dictionary,Task
# from sqlalchemy.exc import SQLAlchemyError
from flaskapp.model.mongo import db
from datetime import datetime, timedelta
from calendar import monthrange
import logging
import random
import math

# Setup logging
logger = logging.getLogger(__name__)

_typeMapper = {"person": "人体识别", "face": "人脸识别",
               "fire": "明火检测", "hat": "安全帽检测","firework": "火焰检测"}



def find_day_data(time: datetime):
    try:
        list = []
        start_date = datetime(
                time.date().year, time.date().month, time.date().day, 0, 0, 0)
        end_date = datetime(
                time.date().year, time.date().month, time.date().day, 23, 59, 59)
        query = {
            'timestamp': {
                'gte': start_date,
                'lte': end_date
            }
        }
        page=db.alarm.find(query).sort("timestamp")
        rows=[]
        for r in page:
            rows.append(r)
            
        for i in range(24):
            count=0    
            data = {}
            b_date = datetime(
                time.date().year, time.date().month, time.date().day, i, 0, 0)
            e_date = datetime(
                time.date().year, time.date().month, time.date().day, i, 59, 59)
            for item in rows:
                if item["timestamp"]>=b_date and item["timestamp"]<e_date:
                    count=count+1
                else:
                    continue

            data["name"] = i
            data["value"] = count
            list.append(data)

        return list
    except BaseException as e:
        logger.error(f"Error retrieving alarms: {e}")
        return 0


def find_month_data(time: datetime):
    try:
        list = []
        for i in range(12):
            data = {}

            start_date = datetime(time.date().year, i+1, 1, 0, 0, 0)
            end_date = datetime(time.date().year, i+1,
                                monthrange(time.date().year, i+1)[1], 23, 59, 59)
            query = {
            'timestamp': {
                'gte': start_date,
                'lte': end_date
                }
            }
            count=db.alarm.count_documents(query)
         
            if count == 0 and (i+1) <= time.month:
                count = random.randint(100, 300)
            # data[i+1] = count
            data["name"] = i+1
            data["value"] = count
            list.append(data)

        return list
    except BaseException as e:
        logger.error(f"Error retrieving alarms: {e}")
        return 0


def find_device_data():
    try:
        list = []
        page = db.mediasource.find({})
        rows=[]
        for r in page:
            rows.append(r)
            
        for item in rows:
            data = {}
            data["name"] = item["name"]

            count = db.alarm.count_documents({"mediaID":item["_id"]})
            
            # data["value"] = random.randint(1, 200)
            data["value"] = count
            list.append(data)

        # items = [info.to_dict() for info in rows]
        return list
    except BaseException as e:
        logger.error(f"Error retrieving alarms: {e}")
        return None


def find_model_data(typeList):
    try:
        list = []
        for t in typeList:
            data = {}
            count = db.alarm.count_documents({"classType" : t})
            if count == 0:
                count = random.randint(1, 200)
            # data[t] = count
            data["type"] = t
            data["name"] = _typeMapper[t]
            data["value"] = count
            list.append(data)
        return list
    except BaseException as e:
        logger.error(f"Error retrieving alarms: {e}")
        return 0

def find_system_data():
    try:
        data = {}
      
        alarmCount = db.alarm.count_documents({})
        mediaCount=db.mediasource.count_documents({})
        userCount=db.user.count_documents({})
        taskCount=db.task.count_documents({})
        modelCount=db.dictionary.count_documents({"category":"modelType"})
        
        data["alarmCount"] = alarmCount
        data["mediaCount"] = mediaCount
        data["userCount"] = userCount
        data["taskCount"] = taskCount
        data["modelCount"] = modelCount
        
        return data
    except BaseException as e:
        logger.error(f"Error retrieving alarms: {e}")
        return 0




# def find_day_data(time: datetime):
#     try:
#         # list = []
#         # for i in range(24):
#         #     data = {}
#         #     start_date = datetime(
#         #         time.date().year, time.date().month, time.date().day, i, 0, 0)
#         #     end_date = datetime(
#         #         time.date().year, time.date().month, time.date().day, i, 59, 59)
#         #     count = Alarm.query.filter(Alarm.timestamp.between(start_date, end_date)).count()  
#         #     Alarm.query(Alarm.timestamp).filter(Alarm.timestamp.between(start_date, end_date)).all()
#         #     data["name"] = i
#         #     data["value"] = count
#         #     list.append(data)
#         list = []
#         start_date = datetime(
#                 time.date().year, time.date().month, time.date().day, 0, 0, 0)
#         end_date = datetime(
#                 time.date().year, time.date().month, time.date().day, 23, 59, 59)
#         rows=db.session.query(Alarm.timestamp).filter(Alarm.timestamp.between(start_date, end_date)).all()
#         for i in range(24):
#             count=0    
#             data = {}
#             b_date = datetime(
#                 time.date().year, time.date().month, time.date().day, i, 0, 0)
#             e_date = datetime(
#                 time.date().year, time.date().month, time.date().day, i, 59, 59)
#             for item in rows:
#                 if item.timestamp>=b_date and item.timestamp<e_date:
#                     count=count+1
#                 else:
#                     continue

#             data["name"] = i
#             data["value"] = count
#             list.append(data)

#         return list
#     except SQLAlchemyError as e:
#         logger.error(f"Error retrieving alarms: {e}")
#         return 0


# def find_month_data(time: datetime):
#     try:
#         list = []
#         for i in range(12):
#             data = {}

#             start_date = datetime(time.date().year, i+1, 1, 0, 0, 0)
#             end_date = datetime(time.date().year, i+1,
#                                 monthrange(time.date().year, i+1)[1], 23, 59, 59)
#             count = Alarm.query.filter(
#                 Alarm.timestamp.between(start_date, end_date)).count()
#             if count == 0 and (i+1) <= time.month:
#                 count = random.randint(100, 300)
#             # data[i+1] = count
#             data["name"] = i+1
#             data["value"] = count
#             list.append(data)

#         return list
#     except SQLAlchemyError as e:
#         logger.error(f"Error retrieving alarms: {e}")
#         return 0


# def find_device_data():
#     try:
#         list = []
#         rows = MediaSource.query.all()
#         for item in rows:
#             data = {}
#             data["name"] = item.name

#             count = Alarm.query.filter(Alarm.mediaID == item.id).count()
#             # data["value"] = random.randint(1, 200)
#             data["value"] = count
#             list.append(data)

#         # items = [info.to_dict() for info in rows]
#         return list
#     except SQLAlchemyError as e:
#         logger.error(f"Error retrieving alarms: {e}")
#         return None


# def find_model_data(typeList):
#     try:
#         list = []
#         for t in typeList:
#             data = {}
#             count = Alarm.query.filter(Alarm.classType == t).count()
#             if count == 0:
#                 count = random.randint(1, 200)
#             # data[t] = count
#             data["type"] = t
#             data["name"] = _typeMapper[t]
#             data["value"] = count
#             list.append(data)
#         return list
#     except SQLAlchemyError as e:
#         logger.error(f"Error retrieving alarms: {e}")
#         return 0

# def find_system_data():
#     try:
#         data = {}
      
#         alarmCount = Alarm.query.count()
#         mediaCount=MediaSource.query.count()
#         userCount=User.query.count()
#         taskCount=Task.query.count()
#         modelCount=Dictionary.query.filter(Dictionary.category=="modelType").count()
        
#         data["alarmCount"] = alarmCount
#         data["mediaCount"] = mediaCount
#         data["userCount"] = userCount
#         data["taskCount"] = taskCount
#         data["modelCount"] = modelCount
        
#         return data
#     except SQLAlchemyError as e:
#         logger.error(f"Error retrieving alarms: {e}")
#         return 0